﻿using Microsoft.Exchange.WebServices.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using XF.Common;
using XF.Meeting.DAL;
using XF.Meeting.Entity.CommonEntity;
using XF.Meeting.Entity.DTO;
using XF.Meeting.Entity.Query;

namespace EWS
{
    public class O365Helper
    {
        static ExchangeToDbDal dal = new ExchangeToDbDal();
        public List<O365Config> configDT;
        public O365Helper()
        {
            var config = dal.GetAllO365Config(out string strError);
            configDT = TableToList.ToList<O365Config>(config.Result);
            foreach (var con in configDT)
            {
                con.service = GetExchangeService(con);
            }
        }
        private ExchangeService GetExchangeService(O365Config config)
        {
            var _config = new ExchangeService((ExchangeVersion)config.version);
            _config.Credentials = new WebCredentials(config.ewsAccount, UCommonWork.Common.Commons.MD5DecodeString(config.ewsPwd));
            _config.Url = new Uri(config.ewsUrl);
            return _config;
        }
        public List<EmailEntity> getEmailEntityList(MeetingOrder order)
        {
            var entityList = new List<EmailEntity>();
            foreach (var conf in configDT)
            {
                EmailEntity entity = new EmailEntity();

                entity.Subject = order.ConferenceTheme;
                entity.Body = order.ConferenceRemark;
                entity.Start = order.BeginTime;
                entity.End = order.EndTime;
                entity.Location = string.Empty;

                var NewParticipantIDs = order.ParticipantIDs;
                NewParticipantIDs = NewParticipantIDs + order.HostPerson + ',';
                NewParticipantIDs = NewParticipantIDs + order.MinutesPerson + ',';
                string[] ParticipantIDs = NewParticipantIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                string[] CRoomIDs = order.CRoomIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in ParticipantIDs)
                {
                    var users = dal.GetUserEmail(Convert.ToInt32(item));
                    Attendeee attendee = new Attendeee(users.Mail, users.Name);

                    entity.AttendeesList.Add(attendee);
                }

                for (int i = 0; i < CRoomIDs.Length; i++)
                {

                    var room = dal.GetRoomrMailByID(Convert.ToInt32(CRoomIDs[i]));
                    if (CRoomIDs.Length > 1)
                    {
                        entity.Location += room.Name + ",";
                    }
                    else
                    {
                        entity.Location += room.Name;
                    }

                    Attendeee attendee = new Attendeee(room.Mail + conf.Suffix, room.Name);

                    entity.AttendeesList.Add(attendee);
                }

                entity.Subject = order.ConferenceTheme;

                entityList.Add(entity);
            }
            return entityList;
        }

        //public string SendAllEwsMeeting(EmailEntity ap, string SendByEimai, out string itemId) {
        //    foreach (var con in serviceList) {
        //        SendMeeting(ap,)
        //    }
        //}

        public void SendMeeting(ExchangeService service, EmailEntity ap, string SendByEimai, out string itemId)
        {
            try
            {


                service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, SendByEimai);
                //初始化会议对象
                Appointment appointment = new Appointment(service);
                //会议主题
                appointment.Subject = ap.Subject;
                //会议内容
                appointment.Body = ap.Body;
                //会议开始
                appointment.Start = ap.Start;
                //会议结束
                appointment.End = ap.End;
                //会议的位置
                appointment.Location = ap.Location;

                //添加与会者
                foreach (var email in ap.AttendeesList)
                {
                    appointment.RequiredAttendees.Add(new Attendee()
                    {
                        Address = email.Address,
                        Name = email.Name
                    });
                }
                //保存会议
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
                appointment.Save();
                Appointment item = Appointment.Bind(service, appointment.Id);
                itemId = item.ICalUid;



            }
            catch (Exception ex)
            {
                itemId = "";

            }
        }

        /// <summary>
        /// 预约编辑exchange ，type=1 为预约，2为编辑
        /// </summary>
        /// <param name="order"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public List<ItemList> SendMeetingReady(MeetingOrder order, int type = 1)
        {
            List<ItemList> items = new List<ItemList>();
            var itemId = "";
            var isAuto = false;
            var orderUser = "";
            foreach (var conf in configDT)
            {
                EmailEntity entity = new EmailEntity();

                entity.Subject = order.ConferenceTheme;
                entity.Body = order.ConferenceRemark;
                entity.Start = order.BeginTime;
                entity.End = order.EndTime;
                entity.Location = string.Empty;
                entity.Subject = order.ConferenceTheme;
                string[] CRoomIDs = order.CRoomIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);


                for (int i = 0; i < CRoomIDs.Length; i++)
                {

                    var room = dal.GetRoomrMailByID(Convert.ToInt32(CRoomIDs[i]));
                    if (CRoomIDs.Length > 1)
                    {
                        entity.Location += room.Name + ",";
                    }
                    else
                    {
                        entity.Location += room.Name;
                    }

                    Attendeee attendee = new Attendeee(room.Mail + conf.Suffix, room.Name);

                    entity.AttendeesList.Add(attendee);
                }
                var address = dal.GetUserEmail(order.CreatorID);
                if (address.ExchangeType == conf.Id)
                {
                    var NewParticipantIDs = order.ParticipantIDs;
                    NewParticipantIDs = NewParticipantIDs + order.HostPerson + ',';

                    string[] ParticipantIDs = NewParticipantIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var item in ParticipantIDs)
                    {
                        var users = dal.GetUserEmail(Convert.ToInt32(item));
                        Attendeee attendee = new Attendeee(users.Mail, users.Name);

                        entity.AttendeesList.Add(attendee);
                    }
                    orderUser = address.Mail;
                    SendMeeting(conf.service, entity, address.Mail, out itemId);


                }
                else
                {
                    isAuto = true;
                    orderUser = conf.ewsAccount;
                    SendMeeting(conf.service, entity, conf.ewsAccount, out itemId);




                }
                items.Add(new ItemList()
                {
                    exchangeType = conf.O365Type,
                    ItemId = itemId,
                    IsAuto = isAuto,
                    OrderUser = orderUser
                });

            }
            return items;
        }



    }
}
